<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>删除链表的倒数第 N 个结点</title>
  </head>
  <body>
    <script>
      //  给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。

      // 进阶：你能尝试使用一趟扫描实现吗？
      // 输入：head = [1,2,3,4,5], n = 2
      // 输出：[1,2,3,5]
      // -------------------------
      var removeNthFromEnd = function (head, n) {
        if (head.next === null && n === 1) return (head = head.next);
        let arr = [];
        let h = head;
        while (h !== null) {
          arr.push(h);
          h = h.next;
        }
        let arrLen = arr.length;
        if (n === arrLen) {
          head.next = null;
          return arr[1];
        }
        arr[arrLen - n - 1].next = arr[arrLen - n].next;
        return head;
      };
    </script>
  </body>
</html>
